<template>
  <div id="editorImage" class="upload-container">
    <el-button
      :style="{background:color,borderColor:color}"
      icon="el-icon-upload"
      size="mini"
      type="primary"
      @click="showDialoag"
    >上传图片</el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        ref="upload"
        name="upfile"
        :data="uploadData"
        :file-list="fileList"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-error="showFalse"
        class="editor-slide-upload"
        :action="actionUrl"
        :auto-upload="false"
        list-type="picture-card"
        append-to-body
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">上传</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui';
import { getGlobal } from '@/utils/global';
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [],
      uploadData: {
        memo: '',
        code: '',
        type: ''
      }
    };
  },
  created() {
    this.actionUrl = 'http://115.239.175.246:3004/rdlw/import/file';
  },
  methods: {
    showDialoag() {
      this.dialogVisible = true;
      this.fileList = [];
    },
    checkAllSuccess() {
      return Object.keys(this.listObj).every(
        item => this.listObj[item].hasSuccess
      );
    },
    async handleSubmit() {
      // const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message({
          message:
            '请等待所有图像成功上载。如果有网络问题，请刷新页面并重新上传！',
          type: 'warning'
        });
        return;
      }
      this.uploadData.code = '1201';
      this.uploadData.memo = '232323';
      this.uploadData.type = '1';
      await this.$refs.upload.submit();
    },
    handleSuccess(response) {
      if (response.code) {
        Message({
          message: '上传成功',
          type: 'success'
        });
        this.dialogVisible = false;
        const arr1 = [];
        getGlobal().then((all) => {
          arr1.push(`${all.url}${response.dataList}`);
          this.$emit('successCBK', arr1);
        });
      } else {
        Message({
          message: response.msg,
          type: 'warning'
        });
        this.fileList = [];
      }
    },
    showFalse() {
      Message({
        message: '上传失败',
        type: 'warning'
      });
      this.dialogVisible = false;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    }
  }
};
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
